<?php
/**
 * 描述
 * Created by Paco
 * Date: 2018/8/22 Time: 11:36
 */

namespace App\Lib\SMS;


use App\Traits\ApiRespond;

class SendSms
{
    use ApiRespond;
    private $timeout = 86400;
    private $send;

    public function __construct()
    {
        $this->send = new \App\Lib\SMS\Aliyun\SendSms();
    }

    /**
     *
     * 发送登录验证码
     * @author Paco
     * @createTime 2018/8/23 10:01
     * @param $mobile
     */
    public function loginCode($mobile,$ip)
    {
        $this->interval($mobile);

        $this->cache($mobile,$ip);
        $code = $this->randCode($mobile);
        $data = [
            'code' => $code,
            'product' => ''
        ];

        $this->send->loginCode($mobile, $data);
    }


    /**
     *
     * 缓存手机与IP
     * @author Paco
     * @createTime 2018/8/23 10:01
     * @param $mobile
     */
    private function cache($mobile,$ip)
    {
        $this->mobileCache($mobile);
        $this->ipCache($ip);
    }

    /**
     *
     * 限制手机时间段内只能发送10次
     * @author Paco
     * @createTime 2018/8/23 10:00
     * @param $mobile
     * @return bool|mixed
     */
    private function mobileCache($mobile)
    {
        $key = 'sms_mobile_limit_' . $mobile;
        if (app('phpredis')->exists($key)) {
            if (app('phpredis')->incr($key) > 10) {
                return $this->respondError(20202);
            }
        } else {
            app('phpredis')->setex($key, 1, $this->timeout);
        }
        return true;
    }


    /**
     *
     * 限制同一IP只能发送10
     * @author Paco
     * @createTime 2018/8/22 17:47
     * @return bool|mixed
     */
    private function ipCache($ip)
    {
        $key = 'sms_ip_limit_' . md5($ip);
        if (app('phpredis')->exists($key)) {
            if (app('phpredis')->incr($key) > 20) {
                return $this->respondError(20202);
            }
        } else {
            app('phpredis')->setex($key, 1, $this->timeout);
        }
        return true;
    }

    /**
     *
     * 每个手机号发送验证码间隔时间
     * @author Paco
     * @createTime 2018/8/22 17:46
     * @param $mobile
     * @return bool|mixed
     */
    private function interval($mobile)
    {
        $key = 'sms_interval_' . $mobile;
        if (app('phpredis')->exists($key)) {
            return $this->respondError(20202);
        } else {
            app('phpredis')->setex($key, 1, 60);
        }
        return true;
    }

    /**
     *
     * 生成随机验证码
     * @author Paco
     * @createTime 2018/8/22 17:46
     * @param $mobile
     * @return int
     */
    private function randCode($mobile)
    {
        $code = rand(100000, 999999);
        app('phpredis')->setex('sms_code_' . $mobile, 600, $code);
        return $code;
    }


}